package com.store.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.store.dto.RefundApplyRequest;
import com.store.dto.RefundHandleRequest;
import com.store.entity.*;
import com.store.mapper.*;
import com.store.vo.RefundRecordVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 退货服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RefundService {
    
    private final RefundRecordMapper refundRecordMapper;
    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;
    private final ProductMapper productMapper;
    private final StockRecordMapper stockRecordMapper;
    private final UserMapper userMapper;
    
    /**
     * 顾客申请退货
     */
    @Transactional(rollbackFor = Exception.class)
    public Long applyRefund(Long userId, RefundApplyRequest request) {
        // 1. 验证订单
        Order order = orderMapper.selectById(request.getOrderId());
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作此订单");
        }
        if (!"completed".equals(order.getStatus()) && !"paid".equals(order.getStatus()) && !"shipped".equals(order.getStatus())) {
            throw new RuntimeException("订单状态不允许退货，只有已支付、已发货或已完成的订单可以申请退货");
        }
        
        // 2. 检查是否已存在退货记录
        LambdaQueryWrapper<RefundRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RefundRecord::getOrderId, request.getOrderId());
        RefundRecord existingRefund = refundRecordMapper.selectOne(queryWrapper);
        if (existingRefund != null) {
            throw new RuntimeException("该订单已申请退货，请勿重复提交");
        }
        
        // 3. 创建退货记录
        RefundRecord refundRecord = new RefundRecord();
        refundRecord.setOrderId(request.getOrderId());
        refundRecord.setRefundAmount(order.getTotalAmount());
        refundRecord.setRefundReason(request.getRefundReason());
        refundRecord.setStatus("pending");
        
        refundRecordMapper.insert(refundRecord);
        
        log.info("用户{}申请退货，订单ID：{}，退货ID：{}", userId, request.getOrderId(), refundRecord.getId());
        
        return refundRecord.getId();
    }
    
    /**
     * 员工/管理员处理退货
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleRefund(Long handlerId, Long refundId, RefundHandleRequest request) {
        // 1. 验证退货记录
        RefundRecord refundRecord = refundRecordMapper.selectById(refundId);
        if (refundRecord == null) {
            throw new RuntimeException("退货记录不存在");
        }
        if (!"pending".equals(refundRecord.getStatus())) {
            throw new RuntimeException("退货记录已处理，无法重复操作");
        }
        
        // 2. 验证订单
        Order order = orderMapper.selectById(refundRecord.getOrderId());
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 3. 如果同意退货，执行退货操作并恢复库存
        if ("approved".equals(request.getStatus()) || "completed".equals(request.getStatus())) {
            // 恢复库存并更新订单状态
            List<OrderItem> items = getOrderItems(order.getId());
            for (OrderItem item : items) {
                Product product = productMapper.selectById(item.getProductId());
                if (product != null) {
                    int beforeStock = product.getStock();
                    int afterStock = beforeStock + item.getQuantity();
                    
                    // 更新商品库存和销量
                    product.setStock(afterStock);
                    product.setSales(Math.max(0, product.getSales() - item.getQuantity()));
                    productMapper.updateById(product);
                    
                    // 记录库存变动
                    StockRecord stockRecord = new StockRecord();
                    stockRecord.setProductId(item.getProductId());
                    stockRecord.setChangeType("refund");
                    stockRecord.setChangeQuantity(item.getQuantity());
                    stockRecord.setBeforeStock(beforeStock);
                    stockRecord.setAfterStock(afterStock);
                    stockRecord.setOrderId(order.getId());
                    stockRecord.setOperatorId(handlerId);
                    stockRecord.setRemark("退货退款：订单号" + order.getOrderNo());
                    stockRecordMapper.insert(stockRecord);
                }
            }
            
            // 更新订单状态为已退款
            order.setStatus("refunded");
            orderMapper.updateById(order);
            
            log.info("处理人{}同意退货，订单ID：{}，退货ID：{}", handlerId, order.getId(), refundId);
        } else if ("rejected".equals(request.getStatus())) {
            log.info("处理人{}拒绝退货，订单ID：{}，退货ID：{}", handlerId, order.getId(), refundId);
        }
        
        // 4. 更新退货记录状态（在库存操作之后）
        refundRecord.setStatus(request.getStatus());
        refundRecord.setHandlerId(handlerId);
        refundRecord.setHandleTime(LocalDateTime.now());
        refundRecord.setHandleRemark(request.getHandleRemark());
        refundRecordMapper.updateById(refundRecord);
    }
    
    /**
     * 获取订单明细
     */
    private List<OrderItem> getOrderItems(Long orderId) {
        LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItem::getOrderId, orderId);
        return orderItemMapper.selectList(queryWrapper);
    }
    
    /**
     * 查询用户的退货记录列表
     */
    public List<RefundRecordVO> getRefundListByUser(Long userId) {
        return refundRecordMapper.selectByUserId(userId);
    }
    
    /**
     * 查询所有退货记录（分页）
     */
    public IPage<RefundRecordVO> getRefundList(int page, int pageSize, String status) {
        Page<RefundRecord> pageParam = new Page<>(page, pageSize);
        LambdaQueryWrapper<RefundRecord> queryWrapper = new LambdaQueryWrapper<>();
        
        // 状态筛选
        if (status != null && !status.trim().isEmpty()) {
            queryWrapper.eq(RefundRecord::getStatus, status);
        }
        
        queryWrapper.orderByDesc(RefundRecord::getCreateTime);
        
        IPage<RefundRecord> refundPage = refundRecordMapper.selectPage(pageParam, queryWrapper);
        
        // 转换为VO
        IPage<RefundRecordVO> voPage = refundPage.convert(refund -> {
            RefundRecordVO vo = refundRecordMapper.selectRefundDetailById(refund.getId());
            return vo;
        });
        
        return voPage;
    }
    
    /**
     * 获取退货详情
     */
    public RefundRecordVO getRefundDetail(Long refundId) {
        RefundRecordVO vo = refundRecordMapper.selectRefundDetailById(refundId);
        if (vo == null) {
            throw new RuntimeException("退货记录不存在");
        }
        return vo;
    }
    
    /**
     * 根据订单ID查询退货记录
     */
    public RefundRecordVO getRefundByOrderId(Long orderId) {
        return refundRecordMapper.selectByOrderId(orderId);
    }
    
    /**
     * 取消退货申请（用户自己取消）
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancelRefund(Long userId, Long refundId) {
        RefundRecord refundRecord = refundRecordMapper.selectById(refundId);
        if (refundRecord == null) {
            throw new RuntimeException("退货记录不存在");
        }
        
        // 验证权限
        Order order = orderMapper.selectById(refundRecord.getOrderId());
        if (order == null || !order.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作此退货申请");
        }
        
        if (!"pending".equals(refundRecord.getStatus())) {
            throw new RuntimeException("只有待处理的退货申请才能取消");
        }
        
        // 删除退货记录
        refundRecordMapper.deleteById(refundId);
        
        log.info("用户{}取消退货申请，退货ID：{}", userId, refundId);
    }
}


